<script setup lang='ts'>
import { ElUpload, ElIcon, ElDialog } from 'element-plus'
import { Plus, Download, Delete, ZoomIn } from '@element-plus/icons-vue'
import { computed, ref } from 'vue'
import type { UploadFile } from 'element-plus'
import { BASE_URL } from '@/api'

const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const disabled = ref(false)
const file = ref<any[]>([])
const downloadLink = ref<HTMLAnchorElement | null>(null)
const { uploadUrl, name, isAvatar } = defineProps({
  uploadUrl: {
    type: String,
    default: ''
  },
  name: {
    type: String,
    default: 'file'
  },
  isAvatar: {
    type: Boolean,
    default: false
  }
})

// 上传的图片的后端访问地址
// const imgUrl = ref<string>('')

const emit = defineEmits(['handleUploadSuccess', 'handleUploadError'])

const setFile = (newFile: any) => {
  file.value = newFile
}

// 上传地址
const fileUploadUrl = computed(() => {
  if (!uploadUrl) {
    console.error('请传入上传地址: MyUpload组件缺少 uploadUrl属性');
    throw new Error('请传入上传地址: MyUpload组件缺少 uploadUrl属性');
  }

  const basePath = import.meta.env.VITE_API_BASE_PATH;
  if (!basePath) {
    console.error('环境变量 VITE_API_BASE_PATH 未配置');
    throw new Error('环境变量 VITE_API_BASE_PATH 未配置');
  }

  return basePath + uploadUrl;
})

// 删除图片
const handleRemove = (curFile: UploadFile) => {
  file.value = file.value.filter((item: any) => item.uid !== curFile.uid)
}

// 图片预览
const handlePictureCardPreview = (file: UploadFile) => {
  dialogImageUrl.value = file.url!
  dialogVisible.value = true
}

// 图片下载
const handleDownload = (file: UploadFile) => {
  // console.log(file)
  if (downloadLink.value) {
    downloadLink.value.href = file.url!
    downloadLink.value.download = file.name || 'downloaded-image'
    downloadLink.value.click()
  }
}

// 上传成功
const handleUploadSuccess = (response: any, uploadFile: any) => {
  // console.log(uploadFile);
  if (response.code === 200) {
    dialogImageUrl.value = URL.createObjectURL(uploadFile.raw!)
    // console.log(dialogImageUrl.value);
    // bookForm.value.cover = uploadFile.response.data.filename;
    // bookForm.value.cover.push({ url: response.data.url });
    // console.log(bookForm.value.coverFile);
    // ElMessage.success('上传成功');
    // console.log(response);
    // imgUrl.value = response.data.url;
    // console.log(file);
    if(isAvatar){
      file.value = [uploadFile]
    }
    emit('handleUploadSuccess', response, uploadFile)
  } else {
    // ElMessage.error('上传失败');
  }
}

const handleUploadError = (error: any, uploadFile: any, uploadFiles: any) => {
  emit('handleUploadError', error, uploadFile, uploadFiles)
};

defineExpose({
  file,
  setFile
})

</script>
<template>
  <div>
    <el-upload accept="image/*" v-model:file-list="file" :name="name" :show-file-list="isAvatar ? false : true"
      class="avatar-uploader" :on-success="handleUploadSuccess" :on-error="handleUploadError" :action="fileUploadUrl"
      list-type="picture-card" :auto-upload="true">
      <template v-if="isAvatar">
        <img v-if="file.length" :src="BASE_URL + '/files' + '/' + file[0].response?.data.url" class="avatar" />
        <el-icon v-else class="avatar-uploader-icon">
          <Plus />
        </el-icon>
      </template>
      <el-icon v-else>
        <Plus />
      </el-icon>
      <template v-if="!isAvatar" #file="{ file }">
        <div>
          <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
          <span class="el-upload-list__item-actions">
            <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
              <el-icon><zoom-in /></el-icon>
            </span>
            <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleDownload(file)">
              <el-icon>
                <Download />
              </el-icon>
            </span>
            <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleRemove(file)">
              <el-icon>
                <Delete />
              </el-icon>
            </span>
          </span>
        </div>
      </template>
    </el-upload>
    <!-- 添加隐藏的下载链接 -->
    <a ref="downloadLink" style="display: none;"></a>
    <el-dialog v-model="dialogVisible">
      <img w-full :src="dialogImageUrl" alt="Preview Image" />
    </el-dialog>
  </div>
</template>

<style lang='less' scoped>
:deep(.avatar-uploader .el-upload) {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

:deep(.avatar-uploader .el-upload:hover) {
  border-color: var(--el-color-primary);
}

:deep(.el-icon.avatar-uploader-icon) {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

.avatar {
  width: 100%;
}
</style>